/**
 * 评审通过、废弃按钮
 */

import React from 'react';
import { Button, Balloon, PopConfirm, Field } from '@teamix/ui';
import DoMergeAndDialog from './doMergeAndDialog';
import { PROJECT_WRITE_ROLES, ENUM } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import CloseBtn from './closeBtn';
import intl from '../../../../../../../../../locale';
import utils from 'utils';

export default class StatusButtons extends React.Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      visible: false,
      submitting: false,
    };
  }

  handleClickBtnPass = () => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.props.doAccept(() => {
      this.setState({ submitting: false });
    });
  };

  render() {
    const {
      codeReviewDetail,
      approve_status,
      targetBranchSetting,
      rootState,
      lastMirrorSyncRecord,
    } = this.props;
    const {
      state,
      mergeStatus,
      approve_check_result,
      assignees,
      source_type,
      work_in_progress,
      author,
    } = codeReviewDetail;
    const { role, isArchive } = window.FORCE.pathResource;

    const { sourceBranchExist, targetBranchExist } =
      rootState && rootState.pageInfo ? rootState.pageInfo.codeReviewDetail : {};

    const index = assignees.findIndex(
      (item) => item.status === 'approved' && item.id === Number(window.FORCE.user.codeUserId),
    );

    const hasApprovedByMe = index > -1;
    const approveBtnText = hasApprovedByMe
      ? intl.get({
          id: 'code-assets.components.mrTitleInfo.statusBtns.Passed',
          defaultMessage: '已通过',
        })
      : intl.get({
          id: 'code-assets.components.mrTitleInfo.statusBtns.Pass',
          defaultMessage: '通过',
        });

    // 是否不允许创建者通过
    const isNotAllowSelfApproval =
      targetBranchSetting &&
      targetBranchSetting.merge_request &&
      targetBranchSetting.merge_request.required &&
      !targetBranchSetting.merge_request.allow_self_approval;
    // 是否设置仅管理员通过,因为设置必须有管理员，直接根据长度判断即可
    const isOnlyAdminApproval =
      targetBranchSetting &&
      targetBranchSetting.merge_request &&
      targetBranchSetting.merge_request.required &&
      targetBranchSetting.merge_request.allow_merge_request.length === 1;

    let isMirrorSynchronizing = false;
    if (lastMirrorSyncRecord) {
      isMirrorSynchronizing = utils.isMirrorSynchronizing(lastMirrorSyncRecord.sync_status);
    }

    let approveBtnJsx;
    switch (approve_status.approve_status) {
      case 'READY_APPROVE':
        // 有权限通过但是没点，对应原来的false，此时为可点击的“通过”按钮
        approveBtnJsx = (
          <Balloon.Tooltip
            trigger={
              <Button
                type="primary"
                onClick={this.handleClickBtnPass}
                loading={this.state.submitting}
              >
                {approveBtnText}
              </Button>
            }
            align="t"
            text={intl.get({
              id: 'code-assets.components.mrTitleInfo.statusBtns.ThroughCodeReviewYouAgree',
              defaultMessage: '通过代码评审表示你赞同本次合并',
            })}
          />
        );

        break;
      case 'APPROVED':
        // 已通过，对应原来接口是true的情况，此时按钮为“已通过”不可点击状态
        // 还要看是不是自己通过了
        if (hasApprovedByMe) {
          approveBtnJsx = (
            <Button type="primary" onClick={this.props.doAccept} disabled>
              {approveBtnText}
            </Button>
          );
        } else if (
          isOnlyAdminApproval ||
          (author.id === Number(window.FORCE.user.codeUserId) && isNotAllowSelfApproval)
        ) {
          // 缺陷： https://teambition.alibaba-inc.com/task/5e9d3a8b5546346a733f73bf
          // 自己是创建者，看下是否设置不允许创建者通过
          approveBtnJsx = (
            <Balloon.Tooltip
              trigger={
                <Button type="primary" disabled>
                  {approveBtnText}
                </Button>
              }
              align="t"
              text={
                isOnlyAdminApproval
                  ? intl.get({
                      id: 'code-assets.components.mrTitleInfo.statusBtns.SetToAllowOnlyAdministrators',
                      defaultMessage: '已设置仅允许管理员通过',
                    })
                  : intl.get({
                      id: 'code-assets.components.mrTitleInfo.statusBtns.TheCreatorIsNotAllowed',
                      defaultMessage: '已设置不允许创建者本人通过',
                    })
              }
            />
          );
        } else {
          approveBtnJsx = (
            <Balloon.Tooltip
              trigger={
                <Button
                  type="primary"
                  onClick={this.handleClickBtnPass}
                  loading={this.state.submitting}
                >
                  {approveBtnText}
                </Button>
              }
              align="t"
              text={intl.get({
                id: 'code-assets.components.mrTitleInfo.statusBtns.ThroughCodeReviewYouAgree',
                defaultMessage: '通过代码评审表示你赞同本次合并',
              })}
            />
          );
        }
        break;
      case 'NO_ACCESS':
        // 无权限通过，显示灰掉的“通过”按钮，悬浮上去给出提示：无权限/No access
        approveBtnJsx = (
          <Balloon.Tooltip
            trigger={
              <Button type="primary" onClick={this.props.doAccept} disabled>
                {approveBtnText}
              </Button>
            }
            align="t"
            text={
              approve_status.message ||
              intl.get({
                id: 'code-assets.components.mrTitleInfo.statusBtns.NoPermission',
                defaultMessage: '无权限',
              })
            }
          />
        );

        break;
      // 评审关闭时会出现这种状态
      case 'METHOD_NOT_ALLOW':
        // 因评审状态不对不允许通过（理论上不会出现这个情况），显示灰掉的“通过”按钮，悬浮上去给出提示：状态异常/Illegal state
        // approveBtnJsx = (
        //   <Balloon.Tooltip
        //     trigger={
        //       <Button type="primary" onClick={this.props.doAccept} disabled>
        //         {approveBtnText}
        //       </Button>
        //     }
        //     align="t"
        //     text={approve_status.message || '状态异常'}
        //   />
        // );
        // 注释掉的原因：代码评审被重新打开后，存在短暂的状态：代码评审的状态为accepted，但approve_status为METHOD_NOT_ALLOW，
        // 导致通过按钮会一闪而过。https://teambition.alibaba-inc.com/task/5dcd5d8e2b3f1644e4feb918
        approveBtnJsx = null;
        break;
      default:
        approveBtnJsx = null;
    }

    let mrBtnJsx;
    // 源分支或目标分支是否存在
    if (sourceBranchExist === 'true' && targetBranchExist === 'true') {
      // 先看 work_in_progress,决定是否显示WIP提示
      if (work_in_progress) {
        mrBtnJsx = (
          <div>
            <Balloon.Tooltip
              trigger={
                <Button type="primary" disabled>
                  {intl.get({
                    id: 'code-assets.components.mrTitleInfo.statusBtns.Merge',
                    defaultMessage: '合并',
                  })}
                </Button>
              }
              align="tl"
              text={intl.get({
                id: 'code-assets.components.mrTitleInfo.statusBtns.TheDevelopmentHasBeenMarked',
                defaultMessage: '已标记开发未完成，如需合并请先删除标题的 WIP 前缀',
              })}
            />
          </div>
        );

        // 再看是否有冲突
      } else if (mergeStatus === 'can_be_merged') {
        // 卡点是否通过
        if (approve_check_result.unsatisfied_check_results.length === 0 && state === 'accepted') {
          mrBtnJsx = (
            <div>
              <DoMergeAndDialog {...this.props} />
            </div>
          );

          // 需求：mr的目标分支设置了不允许开发者合并，“合并”按钮应该置灰
          // https://teambition.alibaba-inc.com/task/5dbbf30b6743ac3950235bfd
          // 能走到这里，至少是DEVELOPER角色了，具备写权限。还需要查询保护分支配置，是否允许DEVLOPER合并
          // 1. 是否有保护分支配置，为空则不处理
          if (
            targetBranchSetting &&
            targetBranchSetting.allow_merge &&
            targetBranchSetting.allow_merge.length
          ) {
            // 2. 管理员肯定可以合并，如果当前用户是DEVELOPER，看分支配置里是否允许DEVELOPER
            const allowMerges = targetBranchSetting.allow_merge;
            const developValue = ENUM.access_level_id.DEVELOPER;
            const hasAllowMergeDesignatedUsers =
              targetBranchSetting?.allow_merge_user_ids?.includes(
                Number(window.FORCE.user.codeUserId),
              );
            if (
              role === 'DEVELOPER' &&
              !allowMerges.includes(developValue) &&
              !hasAllowMergeDesignatedUsers
            ) {
              mrBtnJsx = (
                <div>
                  <Balloon.Tooltip
                    trigger={
                      <Button type="primary" disabled>
                        {intl.get({
                          id: 'code-assets.components.mrTitleInfo.statusBtns.Merge',
                          defaultMessage: '合并',
                        })}
                      </Button>
                    }
                    align="t"
                    text="暂无权限合并，管理员已设置目标分支的合并规则限制"
                  />
                </div>
              );
            }
          }
        } else {
          mrBtnJsx = (
            <div>
              <Balloon.Tooltip
                trigger={
                  <Button type="primary" disabled>
                    {intl.get({
                      id: 'code-assets.components.mrTitleInfo.statusBtns.Merge',
                      defaultMessage: '合并',
                    })}
                  </Button>
                }
                align="t"
                text={intl.get({
                  id: 'code-assets.components.mrTitleInfo.statusBtns.MergeRequirementsNotMet',
                  defaultMessage: '未达到合并要求',
                })}
              />
            </div>
          );
        }
      } else {
        mrBtnJsx = (
          <div>
            <Balloon.Tooltip
              trigger={
                <Button type="primary" disabled>
                  {intl.get({
                    id: 'code-assets.components.mrTitleInfo.statusBtns.Merge',
                    defaultMessage: '合并',
                  })}
                </Button>
              }
              align="t"
              text={intl.get({
                id: 'code-assets.components.mrTitleInfo.statusBtns.ConflictsExistMergeIsNot',
                defaultMessage: '存在冲突，不允许合并',
              })}
            />
          </div>
        );
      }
    } else {
      mrBtnJsx = (
        <div>
          <Balloon.Tooltip
            trigger={
              <Button type="primary" disabled>
                {intl.get({
                  id: 'code-assets.components.mrTitleInfo.statusBtns.Merge',
                  defaultMessage: '合并',
                })}
              </Button>
            }
            align="t"
            text={intl.get({
              id: 'code-assets.components.mrTitleInfo.statusBtns.TheSourceOrDestinationBranch',
              defaultMessage: '源分支或目标分支已不存在',
            })}
          />
        </div>
      );
    }

    let result = null;
    // 已关闭
    if (state === 'closed') {
      if (access(PROJECT_WRITE_ROLES, role)) {
        result = (
          <div className="mr-btns-wrapper-item">
            {sourceBranchExist === 'true' && targetBranchExist === 'true' ? (
              <Button
                onClick={() => {
                  this.props.modifyCr(
                    {
                      state_event: 'reopen',
                    },

                    () => {
                      // 重新请求日志
                      this.props.getSummaryLogs();
                    },
                  );
                }}
              >
                {intl.get({
                  id: 'code-assets.components.mrTitleInfo.statusBtns.Reopen',
                  defaultMessage: '重新打开',
                })}
              </Button>
            ) : (
              <Balloon.Tooltip
                trigger={
                  <Button disabled>
                    {intl.get({
                      id: 'code-assets.components.mrTitleInfo.statusBtns.Reopen',
                      defaultMessage: '重新打开',
                    })}
                  </Button>
                }
                align="t"
              >
                {intl.get({
                  id: 'code-assets.components.mrTitleInfo.statusBtns.TheSourceOrDestinationBranch',
                  defaultMessage: '源分支或目标分支已不存在',
                })}
              </Balloon.Tooltip>
            )}
          </div>
        );
      } else {
        result = null;
      }
    } else if (state === 'merged') {
      // 合并
      if (access(PROJECT_WRITE_ROLES, role)) {
        result = (
          <div className="mr-btns-wrapper-item">
            {sourceBranchExist === 'true' && source_type !== 'COMMIT' ? (
              <PopConfirm
                triggerType="click"
                align="l"
                type="warning"
                title={intl.get({
                  id: 'code-assets.src.utils.locale.DeleteSourceBranch',
                  defaultMessage: '删除源分支',
                })}
                content={intl.get({
                  id: 'code-assets.src.utils.locale.TheSourceBranchHasBeen',
                  defaultMessage: '源分支已合并到目标分支',
                })}
                onConfirm={() => {
                  this.props.deleteSourceBranch();
                  this.setState({
                    visible: false,
                  });
                }}
                visible={this.state.visible}
                onCancel={() => {
                  this.setState({
                    visible: false,
                  });
                }}
                trigger={
                  <Button
                    onClick={() => {
                      this.setState({
                        visible: true,
                      });
                    }}
                  >
                    {intl.get({
                      id: 'code-assets.src.utils.locale.DeleteSourceBranch',
                      defaultMessage: '删除源分支',
                    })}
                  </Button>
                }
              />
            ) : null}
          </div>
        );
      } else {
        result = null;
      }
    } else {
      // 是不是评审者
      const isAssingee = assignees.findIndex(
        (item) => item.id === Number(window.FORCE.user.codeUserId),
      );

      let curApproveBtn;
      if (isArchive !== 'false') {
        curApproveBtn = null;
      } else if (access(PROJECT_WRITE_ROLES, role)) {
        curApproveBtn = <div className="mr-btns-wrapper-item">{approveBtnJsx}</div>;
      } else if (isAssingee > -1) {
        curApproveBtn = (
          <div className="mr-btns-wrapper-item">
            <Balloon.Tooltip
              trigger={
                <Button type="primary" disabled>
                  {approveBtnText}
                </Button>
              }
              align="tl"
              text={intl.get({
                id: 'code-assets.components.mrTitleInfo.statusBtns.UnableToPassTheReview',
                defaultMessage: '无权限通过评审，需具备库开发者及以上权限',
              })}
            />
          </div>
        );
      } else {
        curApproveBtn = null;
      }
      result = (
        <div className="mr-btns-wrapper">
          {/* 归档不显示通过、合并按钮，
            浏览者、非库成员，通过、合并、关闭、重开均不可见
            特殊处理：浏览者或非库成员被设置为评审者时，显示通过并置灰
          */}
          {curApproveBtn}

          {isArchive === 'false' && access(PROJECT_WRITE_ROLES, role) && !isMirrorSynchronizing ? (
            <div className="mr-btns-wrapper-item">{mrBtnJsx}</div>
          ) : (
            <React.Fragment>
              {isMirrorSynchronizing ? (
                <div className="mr-btns-wrapper-item">
                  <Balloon.Tooltip
                    trigger={
                      <Button type="primary" disabled>
                        {intl.get({
                          id: 'code-assets.components.mrTitleInfo.statusBtns.Merge',
                          defaultMessage: '合并',
                        })}
                      </Button>
                    }
                    align="t"
                    text={intl.get({
                      id: 'code-assets.components.mrTitleInfo.statusBtns.TheRepositoryIsBeingSynchronized',
                      defaultMessage: '仓库同步中，暂不支持操作，请稍后再试',
                    })}
                  />
                </div>
              ) : null}
            </React.Fragment>
          )}

          {access(PROJECT_WRITE_ROLES, role) ? (
            <div className="mr-btns-wrapper-item">
              <CloseBtn {...this.props} />
            </div>
          ) : null}
        </div>
      );
    }

    return result;
  }
}
